<?php
/**
 * memcached服务组管理
 * 
 * @author river_he@eueang.com
 */
final class Kit_Memcache_Manager {
	/**
	 * 设置参数
	 * 
	 * @var array
	 */
	private static $_config = null;
	
	/**
	 * 服务器源
	 * 
	 * @var array
	 */
	private static $_mems = array();
	
	/**
	 * 参数配置
	 * 
	 * @param array $config
	 * @return void
	 */
	public static function setConfig(array $config){
		if(self::$_config === null){
			self::$_config = $config;
		}
	}
	
	/**
	 * 获取memcache连接对象
	 * 
	 * @param string $identity
	 * @return Kit_Memcache
	 */
	public static function getMemcache($identity){
		$return = null;
		if(array_key_exists($identity, self::$_mems)){
			$return = self::$_mems[$identity];
		}else if(array_key_exists($identity, self::$_config)){
			$return = self::createMemcache(self::$_config[$identity], $identity);
			if($return instanceof Kit_Memcache){
				self::$_mems[$identity] = $return;
			}else{
				throw new Kit_Memcache_Exception(502, 'the kit_memcache instance failure');
			}
		}else {
			throw new Kit_Memcache_Exception(501, 'can\'t found  the memcache server config in config file');
		}
		return $return;
	}
	
	/**
	 * 获取memcache服务的信息
	 * 
	 * return array
	 */
	public static function getServerStatus(){
		$return = array();
		if(count(self::$_mems) > 0){
			foreach(self::$_mems as $val){
				$return[$val->getId()] = $val->getStatus();
			}
		}
		return $return;
	} 
	/**
	 * 创建目标memcache
	 * 
	 * @param array $config
	 * @return Kit_Memcache
	 */
	private static function createMemcache(array $config, $id){
		return new Kit_Memcache($config['host'], $config['port'], $id);
	}
}
//end